package com.lingx.service;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.fastjson.JSON;
import com.lingx.utils.HttpUtils;
import com.lingx.utils.TokenUtils;
import com.lingx.utils.Utils;
import com.lingx.web.api.ApiService;

@Component("lingxLingxService")
public class LingxService {
	public static String appid="335ec1fc-1011-11e5-b7ab-74d02b6b5f61";
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private ApiService apiService;
	private static final Map<String,String> configs=Collections.synchronizedMap(new HashMap<String,String>());
	
	@PostConstruct
	public void init() {
		resetConfigValue();
	}
	public String getUserIdByToken(String token) {
		return TokenUtils.getTokenDataUserId(token);
	}
	public String getOrgIdByToken(String token) {
		String orgid=getOrgIdsByToken(token);
		if(orgid.indexOf(",")>0)orgid=orgid.split(",")[0];
		return orgid;
	}
	public String getOrgIdsByToken(String token) {
		return TokenUtils.getTokenData(token).getOrgIds();
	}
	public String uuid() {
		return UUID.randomUUID().toString();
	}

	public String ts() {
		return Utils.getTime();
	}

	public String passwordEncode(String password, String userid) {
		return Utils.lingxPasswordEncode(password, userid);
	}

	public String getTime() {
		return ts();
	}

	public String arrayToString(String[] arr) {
		StringBuilder sb=new StringBuilder();
		for(String temp:arr){
			sb.append(temp).append(",");
		}
		if(sb.length()>0){sb.deleteCharAt(sb.length()-1);}
		return sb.toString();
	}
	public String[] stringToArray(String str) {
		return str.split(",");
	}
	public int queryForInt(String sql, Object... objects) {
		return this.jdbcTemplate.queryForObject(sql, Integer.class,objects);
	}
	
	public String getConfigValue(String key, String defaultValue) {
		if (configs.containsKey(key)) {
			return configs.get(key);
		} else {
			String time=Utils.getTime();
			if(this.queryForInt("select count(*) from tlingx_config where config_key=?",key)==0){
				this.jdbcTemplate.update("insert into tlingx_config(id,name,config_key,config_value,status,create_time,modify_time,remark,app_id) values(?,?,?,?,?,?,?,?,?)"
						,uuid(),"未设置",key,defaultValue,1,time,time,"自动生成",appid);
			}
			configs.put(key, defaultValue);
			return defaultValue;
		}
	}
	public void setConfigValue(String key, String value) {
		this.jdbcTemplate.update("update tlingx_config set config_value=?,modify_time=? where config_key=?",value,Utils.getTime(),key);
		configs.put(key, value);
	}

	public void resetConfigValue() {
		try {
			configs.clear();
			List<Map<String,Object>> list=this.jdbcTemplate.queryForList("select config_key,config_value from tlingx_config where status=1 ");
			for(Map<String,Object> map:list){
				configs.put(map.get("config_key").toString(), map.get("config_value").toString());
			}
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
	}
	
	public void logOperate(String userid,String content,String ip,Map<String,Object> reqMap,String res) {
		Map<String,Object> newMap=new HashMap<>();
		newMap.putAll(reqMap);
		newMap.remove("lingxtoken");
		String req=JSON.toJSONString(newMap);
		
		if(req.length()>500) req=req.substring(0,500);
		String sql="insert into tlingx_operate_log(user_id,content,ip,ts,req,res)values(?,?,?,?,?,?)";
		this.jdbcTemplate.update(sql,userid,content,ip,Utils.getTime(),req,res);
		
	}
	/**
	 * 后期改为httpPost
	 * @param apiUrl
	 * @param params
	 * @return
	 */
	public String callApi(String apiUrl,String params) {
		String ret="";
		ret=HttpUtils.post(apiUrl, params);
		return ret;
	}
	public String httpPost(String apiUrl,String params) {
		String ret="";
		ret=HttpUtils.post(apiUrl, params);
		return ret;
	}
	public void pushMessage(String userid,String content) {
		this.pushMessage(userid, content, "");
	}
	public void pushMessage(String userid,String content,String route_path) {
		String time=Utils.getTime();
		this.jdbcTemplate.update("insert into tlingx_message(content,to_user_id,from_user_id,type,status,is_push,route_path,create_time,read_time) values(?,?,?,?,?,?,?,?,?)",
				content,userid,"",1,1,0,route_path,time,time);
	}
	
	public ApiService api() {
		return this.apiService;
	}
	public boolean exec(String name) {
		String path=System.getProperty("user.dir");
		
		try {
			if(Desktop.isDesktopSupported()) {
				System.out.println("exec-> "+path+"/"+name+".bat");
				Desktop.getDesktop().open(new File(path+"/"+name+".bat"));
			}else {
				Runtime run = Runtime.getRuntime();
				System.out.println("exec-> "+path+"/"+name+".sh");
				Process p = run.exec("sh "+path+"/"+name+".sh"); 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	public List<Map<String,Object>> getListByExcel(String path){
		String root=System.getProperty("user.dir");
		File file=new File(root+"/files/"+path);
		ExcelReaderBuilder erb=EasyExcel.read(file);
		List<Map<String,Object>> list=erb.doReadAllSync();
		return list;
	}
	public int importDatabaseByList(String sql,List<Map<String,Object>> list,int num) {
		int c=0;
		Object array[]=new Object[num];
		for(Map<String,Object> map:list) {
			for(int i=0;i<num;i++) {
				array[i]=map.get(i);
			}
			c=+this.jdbcTemplate.update(sql,array);
		}
		return c;
	}
}
